<!-- 采购管理-采购任务列表 -->
<template>
  <pageHeader title="新建采购申请" :breadCrumb="breadCrumb" :show-back="true">
    <template #footer
      ><a-space>
        <a-button @click="router.back()">
          <template #default>取消</template>
        </a-button>
        <a-button type="primary" @click="handleClick">
          <template #default>提交</template>
        </a-button></a-space
      >
    </template>
    <div class="title">
      <h1>采购申请表</h1>
    </div>
    <div>
      <div class="title-item">
        <a-space style="margin-left: 40px">
          <div
            style="
              width: 5px;
              height: 23px;
              background-color: rgba(61, 126, 255, 1);
              border: none;
              border-radius: 2px;
            "
          ></div>
          <div>基本信息</div></a-space
        >
      </div>
      <div class="demand-index">
        <a-form
          ref="refForm"
          :model="demand.info"
          autoLabelWidth
          :layout="(layout as Tlayout)"
        >
          <a-row :gutter="16">
            <a-col
              v-for="item in demandForm?.info?.design?.form"
              :key="item.id"
              :span="item.span"
            >
              <FormItem
                :name="item.name"
                :componentType="item.componentType"
                v-model:props="item.props"
                :required="item.required"
                v-model:values="item.values"
              />
            </a-col>
          </a-row>
        </a-form>
      </div>
    </div>
  </pageHeader>

  <a-modal v-model:visible="visible" @ok="handleOk" @cancel="handleCancel">
    <template #title> 审核信息 </template>
    <div
      ><a-form :model="demand" auto-label-width>
        <a-form-item field="priority" label="优先级">
          <a-radio-group v-model="demand.info.priority">
            <a-radio :value="4">紧急</a-radio>
            <a-radio :value="3">高</a-radio>
            <a-radio :value="2">中</a-radio>
            <a-radio :value="1">低</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form></div
    >
  </a-modal>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, onMounted, onUnmounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { useBuyStore } from '@/store';

  import {
    postPurchaseApply,
    PutPurchaseApplyList,
  } from '@/api/buy-management/buy-apply/index';
  import { getOpenTemp } from '@/api/buy-management/get-template/index';

  const buyStore = useBuyStore();
  const router = useRouter();
  const layout = ref('vertical');
  let userData = JSON.parse(sessionStorage.getItem('loginInfo') as any);
  type Tlayout = 'inline' | 'horizontal' | 'vertical' | undefined;
  const breadCrumb: string[] = ['采购管理', '采购管理', '新建采购申请'];
  interface DemandType {
    info: {
      number: string;
      name: string;
      createBy: number;
      deptId: number;
      phone: string;
      applyTime: string;
      deliveryTime: string;
      priority: number;
      state: number;
      description: string;
      templateId: number;
      flowId: number;
      file_id: number;
      extend: string;
      product: any;
      file: any;
    };
  }
  const demand = reactive<DemandType>({
    info: {
      number: '',
      name: '',
      createBy: 0,
      deptId: 0,
      phone: '',
      applyTime: '',
      deliveryTime: '',
      priority: 0,
      state: 0,
      description: '',
      templateId: 0,
      flowId: 0,
      file_id: 0,
      extend: '',
      product: [],
      file: [],
    },
  });
  interface DemandFormType {
    info: {
      id: number;
      flowId: number;
      design: {
        form: any[];
      };
    };
  }
  const demandForm = reactive<DemandFormType>({
    info: { id: 0, flowId: 0, design: { form: [] } },
  });

  const getTemp = async () => {
    const res = await getOpenTemp({ type: 1 });
    demandForm.info = res;
    demandForm.info.design.form.sort((a: any, b: any) => a.sort - b.sort);
    demandForm.info.design.form.forEach((item: any) => {
      item.props = JSON.parse(item.props);
      if (item.values !== '') {
        item.values = JSON.parse(item.values);
        if (item.values[0] === '') {
          item.values = [];
        }
      }
      if (item.code === 'CREATED_DY') {
        item.values = [userData.id];
      }
      if (item.code === 'APPLY_DEPT') {
        item.values = [userData.department.id];
      }
      if (buyStore.productionToProcurement) {
        if (item.code === 'APPLY_DETAILED') {
          item.props.data = buyStore.productionToProcurement;
        }
      }
    });
  };
  getTemp();

  const visible = ref(false);
  const keys = Object.keys(demand.info);

  let refForm = ref();
  const handleClick = async () => {
    if (!(await refForm.value.validate())) {
      visible.value = true;
    }
  };

  const handleOk = async () => {
    visible.value = false;
    demandForm.info.design.form.forEach((item) => {
      if (item.code === 'APPLY_DETAILED') {
        demand.info.product = item.props.data;
      }
      if (item.code === 'FILE') {
        if (!item.props.data.length) return;
        demand.info.file = item.props.data;
        demand.info.file[0].moduleType = 1;
        delete demand.info.file[0].id;
      }
      if (item.code === 'APPLY_DATE') {
        demand.info.applyTime = item.values[0]
          ? new Date(item.values[0]).toJSON()
          : new Date().toJSON();
      }
      if (item.fieldName && keys.includes(item.fieldName)) {
        demand.info[item.fieldName] = item.values[0];
      }
    });
    demand.info.product.forEach((item) => {
      item.deliveryTime = new Date(item.deliveryTime).toJSON();
    });
    demand.info.applyTime = new Date().toJSON();
    demand.info.deliveryTime = new Date().toJSON();
    demand.info.state = 1;
    demand.info.templateId = demandForm.info.id;
    demand.info.extend = JSON.stringify(demandForm.info.design.form);
    await postPurchaseApply(demand.info);
    router.back();
  };
  const handleCancel = () => {
    visible.value = false;
  };

  onUnmounted(() => {
    buyStore.productionToProcurement = [];
  });
</script>

<style scoped lang="less">
  // .content-head {
  // }
  .title {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .title-item {
    width: 95%;
    height: 60px;
    margin: auto;
    background-color: rgba(245, 247, 250);
    line-height: 60px;
    margin-top: 20px;
  }
  .demand-index {
    padding: 25px 140px;
  }

  .box {
    padding-top: 10px;
    margin-top: 20px;
    border-top: 1px solid #e4e4e4;
    display: flex;
    justify-content: end;
    width: 100%;
  }
</style>
